import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  ToastAndroid,
  TouchableOpacity,
  TouchableWithoutFeedback, Keyboard, Alert,
} from "react-native";
import {getData, saveData} from '../utils/storageUtils';
import useHideTabBar from '../utils/useHideTabBar';
import { CustomText } from "../customview/CustomText";
import theme from '../utils/theme';
import { normalize } from "../utils/commonUtils";
import { showToast } from "../utils/toastUtils";
import API from '../Network/Api';
import Toast from "react-native-toast-message";

const PasswordChangePage = ({navigation}) => {
  const [loginPassword, setLoginPassword] = useState('');
  const [newLoginPassword, setNewLoginPassword] = useState('');
  const [payPassword, setPayPassword] = useState('');
  const [newPayPassword, setNewPayPassword] = useState('');
  const [phone, setPhone] = useState('');

  useHideTabBar(navigation);
  useEffect(() => {
    const fetchPasswords = async () => {
      const loginInfo = await getData('userInfoKey');
      if (loginInfo) {
        if (loginInfo.loginPassword) {
          setLoginPassword(loginInfo.loginPassword);
        }
        if (loginInfo.payPassword) {
          setPayPassword(loginInfo.payPassword);
        }
        if (loginInfo.phone) {
          setPhone(loginInfo.phone);
        }
      }
    };
    fetchPasswords();
  }, []);

  const handlePasswordChange = () => {
    if (newPayPassword.trim() === '' && newLoginPassword.trim() === '') {
      return;
    }
    if (newLoginPassword.length < 6 && newLoginPassword.length > 0) {
      showToast({text2: '登录密码不能低于6位！'});
      return;
    }
    if (newPayPassword.length < 6 && newPayPassword.length > 0) {
      showToast({text2: '支付密码不能低于6位！'});
      return;
    }
    API.modifyUserPasswordReq(
      newLoginPassword || loginPassword,
      newPayPassword || payPassword,
      phone,
    )
      .then(response => {
        if (response.resultCode === '1') {
          setLoginPassword(newLoginPassword || loginPassword);
          setPayPassword(newPayPassword || payPassword);
          showToast({
            text2: '修改成功',
          });
        } else {
          showToast({
            text2: response.showMsg,
          });
        }
      })
      .catch(error => {
        showToast({
          text2: '修改密码失败，请联系管理员！',
        });
      })
      .finally(() => {
      });
  };

  const handleNewLoginPasswordChange = (text) => {
    const filteredText = text.replace(/\s/g, '');
    setNewLoginPassword(filteredText);
  };
  const handleNewPayPasswordChange = (text) => {
    const filteredText = text.replace(/\s/g, '');
    setNewPayPassword(filteredText);
  };

  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <View style={styles.container}>
        <CustomText style={styles.title}>修改登录密码</CustomText>
        <TextInput
          style={styles.input}
          placeholder="当前登录密码"
          value={loginPassword}
          editable={false}
          allowFontScaling={false}
        />
        <TextInput
          style={styles.input}
          placeholder="新登录密码，不写代表不修改"
          secureTextEntry
          onChangeText={handleNewLoginPasswordChange}
          value={newLoginPassword}
          allowFontScaling={false}
        />

        <CustomText style={styles.title}>修改支付密码</CustomText>
        <TextInput
          style={styles.input}
          placeholder="当前支付密码"
          value={payPassword}
          editable={false}
          allowFontScaling={false}
        />
        <TextInput
          style={styles.input}
          placeholder="新支付密码，不写代表不修改"
          secureTextEntry
          onChangeText={handleNewPayPasswordChange}
          value={newPayPassword}
          allowFontScaling={false}
        />
        <TouchableOpacity style={styles.authenticationButton} onPress={handlePasswordChange}>
          <CustomText style={styles.buttonText}>确认修改</CustomText>
        </TouchableOpacity>
        <Toast />
      </View>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff'
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    marginBottom: 10,
    borderRadius: 5
  },
  authenticationButton: {
    backgroundColor: theme.colors.primary,
    borderRadius: 8,
    alignItems: 'center',
    padding: 15,
    marginTop: 15,
  },
  buttonText: {
    color: '#fff',
    fontSize: normalize(18),
    fontWeight: 'bold',
  },
});

export default PasswordChangePage;
